package com.example.joblinker.interceptor;

import com.example.joblinker.util.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                // 解析token获取用户ID
                Long userId = JwtUtil.getUserId(token);
                // 尝试获取用户角色
                Integer userRole = JwtUtil.getUserRole(token);
                
                // 将用户ID存入request属性
                request.setAttribute("userId", userId);
                // 将用户角色存入request属性
                if (userRole != null) {
                    request.setAttribute("userRole", userRole);
                }
                
                return true;
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
} 